/***********************************************************************
	Copyright (C) 2011 Bertrand GUILLAUMOND
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

************************************************************************/
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.*;
import java.lang.*;
import java.net.*;
import java.security.*;

public class Connection{

	private String user;
	private String password;
	private boolean isAuthenticated;

	public Connection()
	{
		LoginDialog login = new LoginDialog(new JFrame());
        Options opt = new Options();

		login.startDialog(opt);
		this.user = opt.getUser();
		this.password = opt.getPassword();
		isAuthenticated = false;
	}

	public boolean isAuthenticated()
	{
		return isAuthenticated;	
	}

	public void checkAuthentication(String key) throws Exception
	{

		URL u = new URL("http://www.thethirdage.fr/webservices/checkAuthentication?key="+key+"&u="+this.user+"&p="+this.password);
 
		String s;
		BufferedReader r = new BufferedReader(new InputStreamReader(u.openStream()));

		while ((s = r.readLine()) != null) {
				try {
				  if(s.equals("true")){
					System.out.println("Authenticated");
					isAuthenticated = true;
				  }
				  else
					System.out.println("Authentication failed");
				} catch(Exception ie) {
				   ie.printStackTrace();
				}
		}

	}

	public void getMessages(String key) throws Exception
	{
		URL u = new URL("http://www.thethirdage.fr/webservices/getMessages?key="+key+"&u="+this.user+"&p="+this.password);
 
		String s;
		BufferedReader r = new BufferedReader(new InputStreamReader(u.openStream()));
		
		PrintWriter output = null;
		try {
		  output = new PrintWriter(new FileWriter("messages.xml"));
		} catch (IOException e) {
		  System.err.println("# Error : permission denied \""+ "messages.xml" +"\".");
		  System.exit(1);
		}

		while ((s = r.readLine()) != null) {
		    try {
			  output.println(s);
			} catch(Exception ie) {
			   ie.printStackTrace();
			}
		}

		output.close();
		if (output.checkError()) {
		  System.err.println("# Erreur : le fichier \""+ "messages.xml"
		                     + "\" n'a pu être enregistré correctement.");
		  System.exit(1);
		}
	}


	private class LoginDialog extends JDialog implements ActionListener, FocusListener
    {
        private JPanel topPanel;
        private JPanel midPanel;
        private JPanel lowPanel;
        private JButton loginButton;
        private JLabel mainTitle = new JLabel("<html><h1>Login</h1></html>");
        private Options options = null;
 		private JTextField usernameText;
		private JPasswordField passwordText;
        
       	public LoginDialog(JFrame parent)
       	{
		    super(parent,"Connexion au serveur The Third Age",true);
		    setLayout(new GridLayout(3,0,10,10));
		    topPanel = new JPanel();
		    midPanel = new JPanel();
		    lowPanel = new JPanel();

		    topPanel.setLayout(new FlowLayout());
		    midPanel.setLayout(new FlowLayout());
		    lowPanel.setLayout(new FlowLayout());
		                   
		    getContentPane().add(topPanel);
		    getContentPane().add(midPanel);
		    getContentPane().add(lowPanel);

		    addButtons();
		    addEvents();

		    setSize(500,200);
  		}

        public void addButtons()
        {
        	topPanel.add(mainTitle);
         	usernameText = new JTextField("Login", 10);
			passwordText = new JPasswordField("Password", 10);

			midPanel.add(usernameText);
            midPanel.add(passwordText);
  
            loginButton = new JButton("Login");
            lowPanel.add(loginButton);
                        
        }

        public void addEvents()
       	{
        	loginButton.addActionListener(this);
			usernameText.addFocusListener(this);
			passwordText.addFocusListener(this);
        }

        public void actionPerformed(ActionEvent ev)
        {       
            if(options == null){
            	System.out.println("Erreur actionPerformed : les options ne sont pas initialisées");
            	return;
            }

            if(ev.getSource() == loginButton)
            {
				try{
					options.setUser(usernameText.getText());
					options.setPassword(passwordText.getText());	
				}
				catch(Exception e)
				{
					e.printStackTrace();				
				}
            }                   

            setVisible(false);
        }

	public void focusGained(FocusEvent e) {
		if(e.getSource() == usernameText)
        	usernameText.setText("");
		if(e.getSource() == passwordText)
        	passwordText.setText("");
    }

    public void focusLost(FocusEvent e) {
		if(e.getSource() == usernameText && usernameText.getText().equals(""))
	        usernameText.setText("Login");
		if(e.getSource() == passwordText && passwordText.getText().equals(""))
	        passwordText.setText("password");
    }
        
                
        public void startDialog(Options opt)
        {
        	if(opt == null)
        	    System.out.println("Erreur dans startDialog : les options ne sont pas initialisées");
            options = opt;
            setVisible(true);
        }       
        
    }


	private class Options
    {
		String user;
		String pass;
                
       	public Options(){

        }
                
        public void setUser(String u)
        {
        	user = u;
        }

		public void setPassword(String p) throws Exception
        {

			String tohash = this.user+':'+p.toUpperCase();
			tohash = tohash.toUpperCase();
        	pass = Hash.SHA1(tohash);
        }

        public String getUser()
        {
        	return user;
        }

		public String getPassword()
        {
        	return pass;
        }

    }

	
}
